package pyip.lib.mixtool;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

/**
 * @author yepeng
 * @date 2014年12月11日
 */
public class RedirectSysOut {

    public static void main(String[] args) {
        redirctSysOut();
        redirctSysErr();
        System.out.println("welcome");
        System.err.println("error");
    }
    
    // private static final Logger

    public static void redirctSysOut() {
        try {
            PrintStream out = new PrintStream(new FileOutputStream("out.log"));
            PrintStream stream = new DoubleStream(System.out, out);
            System.setOut(stream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    
    public static void redirctSysErr() {
        try {
            PrintStream err = new PrintStream(new FileOutputStream("err.log"));
            PrintStream stream2 = new DoubleStream(System.err, err);
            System.setErr(stream2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static class DoubleStream extends PrintStream {
        PrintStream out;

        public DoubleStream(PrintStream out1, PrintStream out2) {
            super(out1);
            this.out = out2;
        }

        @Override
        public void write(byte buf[], int off, int len) {
            try {
                super.write(buf, off, len);
                out.write(buf, off, len);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void flush() {
            try {
                super.flush();
            } finally {
                out.flush();
            }
        }
    }

}
